import 'package:country_pickers/countries.dart';
import 'package:country_pickers/country.dart';
import 'package:country_pickers/country_pickers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_views/jr_user/jr_user_controller.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_app_bar.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_buttons.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_scaffold.dart';
import 'package:jet_rails/jr_services/jr_services.dart';
import 'package:jet_rails/jr_services/jr_tracking.dart';
import 'package:jet_rails/jr_utils/jr_dialog.dart';
import 'package:jet_rails/jr_utils/jr_media.dart';

class JrEditProfileView extends StatefulWidget {
  const JrEditProfileView({Key? key}) : super(key: key);

  @override
  State<JrEditProfileView> createState() => _JrEditProfileViewState();
}

class _JrEditProfileViewState extends State<JrEditProfileView> {
  final TextEditingController nickNameController = TextEditingController();
  DateTime birthday = DateTime.now();
  late String country;
  int nickNameMaxLength = 30;

  @override
  void initState() {
    nickNameController.text = JrServices.instance.loginUser.value.nickname ?? '';
    country = JrServices.instance.loginUser.value.country ?? '';
    birthday = DateTime.parse(JrServices.instance.loginUser.value.birthday ?? DateTime.now().toString());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return JrScaffold(
        appBar: JrAppBar(
          title: 'About',
        ),
        body: Column(
          children: [
            buildUserPicWidget(),
            SizedBox(height: 32.h),
            buildNicknameWidget(),
            SizedBox(height: 20.h),
            buildDateWidget(),
            SizedBox(height: 20.h),
            buildCountryWidget(),
            const Spacer(),
            buildBottomButton(),
            SizedBox(height: 40.h),
          ],
        ));
  }

  void refreshSubmitStatus({String? name}) {
    name ??= nickNameController.text;
    if (name == JrServices.instance.loginUser.value.nickname &&
        birthday == DateTime.parse(JrServices.instance.loginUser.value.birthday!) &&
        country == JrServices.instance.loginUser.value.country) {
      Get.find<JrUserController>().editInfoCanSubmit.value = false;
    } else {
      Get.find<JrUserController>().editInfoCanSubmit.value = true;
    }
    Get.find<JrUserController>().editInfoCanSubmit.refresh();
  }

  buildUserPicWidget() {
    return GestureDetector(
      onTap: () async {
        JrTracking.click(JrTrackingPages.pageEditAvatar);
        List list = [
          {
            'title': 'Take a picture',
            'onPressed': () async {
              String? imgPath = await JrMedia.instance.takePhoto();
              if (imgPath != null) {
                Get.find<JrUserController>().updateUserAvatarWithDio(imgPath);
              }
            },
          },
          {
            'title': 'Photo album',
            'onPressed': () async {
              String? imgPath = await JrMedia.instance.pickImage();
              if (imgPath != null) {
                Get.find<JrUserController>().updateUserAvatarWithDio(imgPath);
              }
            },
          }
        ];
        JrDialog.showSelectDialog(list);
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        margin: EdgeInsets.only(left: 32.w),
        child: Stack(
          children: [
            Obx(() {
              return Container(
                padding: EdgeInsets.all(1.8.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(49.w)),
                  color: Colors.white,
                ),
                child: CircleAvatar(
                  backgroundColor: Colors.white,
                  radius: 49.w,
                  foregroundImage: (JrServices.instance.loginUser.value.getAvatarUrl.isNotEmpty)
                      ? NetworkImage(JrServices.instance.loginUser.value.getAvatarUrl)
                      : null,
                ),
              );
            }),
            Positioned(
              right: 2.w,
              bottom: 2.w,
              child: Container(
                width: 24.w,
                height: 24.w,
                child: Image.asset('assets/webp/icon_edit_avatar.webp'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  buildNicknameWidget() {
    return Container(
        height: 44.h,
        margin: EdgeInsets.only(left: 32.w, right: 32.w),
        padding: EdgeInsets.only(right: 20.w),
        decoration: BoxDecoration(
          gradient: const LinearGradient(
              colors: [Color(0xFF684069), Color(0xFF9046B4)], begin: Alignment.topLeft, end: Alignment.bottomRight),
          borderRadius: BorderRadius.circular(8.w),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              alignment: Alignment.centerLeft,
              margin: EdgeInsets.only(left: 20.w),
              child: Text(
                'Nick Name',
                style: TextStyle(color: Colors.white54, fontSize: 12.sp),
              ),
            ),
            Expanded(
              child: Container(
                alignment: Alignment.centerLeft,
                child: TextField(
                  controller: nickNameController,
                  maxLines: 1,
                  maxLength: nickNameMaxLength,
                  textAlign: TextAlign.right,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                  ),
                  onChanged: (value) {
                    refreshSubmitStatus(name: value);
                  },
                  decoration: InputDecoration(
                    counterText: '',
                    hintStyle: TextStyle(
                      fontSize: 16.sp,
                    ),
                    border: InputBorder.none,
                  ),
                ),
              ),
            ),
          ],
        ));
  }

  buildDateWidget() {
    return StatefulBuilder(
      builder: (context, setState) => GestureDetector(
        onTap: () {
          DateTime maximumDate = DateTime.now().subtract(const Duration(days: 365 * 18));
          JrDialog.showDatePicker(
            initialDateTime: birthday,
            maximumDate: maximumDate,
            onDateTimeChanged: (value) {
              birthday = value;
              setState(() {});
              refreshSubmitStatus();
            },
          );
        },
        child: Container(
            height: 44.h,
            padding: EdgeInsets.only(right: 20.w),
            margin: EdgeInsets.only(left: 32.w, right: 32.w),
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                  colors: [Color(0xFF684069), Color(0xFF9046B4)], begin: Alignment.topLeft, end: Alignment.bottomRight),
              borderRadius: BorderRadius.circular(8.w),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(left: 20.w),
                  child: Text(
                    'Birthday',
                    style: TextStyle(color: Colors.white54, fontSize: 12.sp),
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.centerRight,
                    child: Text(
                      '${birthday.year}-${birthday.month}-${birthday.day}',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                ),
              ],
            )),
      ),
    );
  }

  buildCountryWidget() {
    return StatefulBuilder(
      builder: (context, setState) => GestureDetector(
        onTap: () {
          showCupertinoModalPopup(
              context: context,
              builder: (BuildContext context) {
                Country? selectCountry;
                for (var c in countryList) {
                  if (c.iso3Code == country) {
                    selectCountry = c;
                    break;
                  }
                }
                return CountryPickerCupertino(
                  diameterRatio: 10,
                  offAxisFraction: 0,
                  initialCountry: selectCountry,
                  pickerSheetHeight: 300.0,
                  onValuePicked: (Country c) {
                    country = c.iso3Code;
                    setState(() {});
                    refreshSubmitStatus();
                  },
                  itemBuilder: (country) {
                    return Row(
                      children: <Widget>[
                        const SizedBox(width: 8.0),
                        CountryPickerUtils.getDefaultFlagImage(country),
                        const SizedBox(width: 8.0),
                        Expanded(child: Text(country.name)),
                      ],
                    );
                  },
                  itemFilter: (c) => !['CN'].contains(c.isoCode),
                );
              });
        },
        child: Container(
            height: 44.h,
            margin: EdgeInsets.only(left: 32.w, right: 32.w),
            padding: EdgeInsets.only(right: 20.w),
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                  colors: [Color(0xFF684069), Color(0xFF9046B4)], begin: Alignment.topLeft, end: Alignment.bottomRight),
              borderRadius: BorderRadius.circular(8.w),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(left: 20.w),
                  child: Text(
                    'Country',
                    style: TextStyle(color: Colors.white54, fontSize: 12.sp),
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.centerRight,
                    child: Text(
                      country,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                ),
              ],
            )),
      ),
    );
  }

  Widget buildBottomButton() {
    return Obx(
      () {
        return Container(
          margin: EdgeInsets.symmetric(horizontal: 24.w),
          child: JrGradientButton(
            text: 'Submit',
            gradient: Get.find<JrUserController>().editInfoCanSubmit.value == true
                ? null
                : const LinearGradient(colors: [Colors.grey, Colors.grey]),
            onTap: () {
              if (Get.find<JrUserController>().editInfoCanSubmit.value == true) {
                Get.find<JrUserController>().updateUserInfo(nickNameController.text, birthday, country);
              }
            },
          ),
        );
      },
    );
  }
}
